﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Web.UI;

namespace AsNum.Common.EntLib.Validation {
    public class MapBuilder<TEntity> {

        private Dictionary<string , Tuple<string , string>> maps;
        public Dictionary<string , Tuple<string,string>> Maps {
            get {
                if ( this.maps == null )
                    this.maps = new Dictionary<string , Tuple<string,string>> ( );
                return this.maps;
            }
            private set {
                this.maps = value;
            }
        }

        public MapBuilder() {

        }

        public MapBuilder<TEntity> Map(Expression<Func<TEntity , object>> property , Control control, string label = "") {
            var propertyName = GetPropertyName ( property );
            return this.Map ( propertyName , control.UniqueID, label );
        }

        public MapBuilder<TEntity> Map(string property , Control control, string label = "") {
            return Map ( property , control.UniqueID, label );
        }

        public MapBuilder<TEntity> Map(string property , string control, string label = "") {
            if ( !this.Maps.ContainsKey ( control ) )
                this.Maps.Add ( control , Tuple.Create<string,string>( property, label) );
            return this;
        }

        private static string GetPropertyName(LambdaExpression property) {
            var member = property.Body as MemberExpression;
            if ( member == null ) {
                var unaryExpression = ( UnaryExpression )property.Body;
                member = ( MemberExpression )unaryExpression.Operand;
            }

            return string.Format ( "{0}.{1}" , member.Member.ReflectedType.FullName , member.Member.Name );
        }
    }
}
